#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
import MySQLdb
import time
import os
import hashlib

file = sys.argv[1]
host = sys.argv[2]
port = sys.argv[3]
user = sys.argv[4]
password = sys.argv[5]
db = sys.argv[6]
day = sys.argv[7]
level = sys.argv[8]

def format_path(s):
    if s and s == '0':
        return '直接来源'
    return s

def format_url(u):
    if u:
        return u[:255]

columns_dict = {'1':['cid,sid,referer,session,day,update_time', 'nas_behaviour_visitpath_referer'], '2':['cid,sid,referer,page1,session,day,update_time', 'nas_behaviour_visitpath_page1'], '3':['cid,sid,referer,page1,page2,session,day,update_time', 'nas_behaviour_visitpath_page2'], '4':['cid,sid,referer,page1,page2,page3,session,day,update_time', 'nas_behaviour_visitpath_page3'], '5':['cid,sid,referer,page1,page2,page3,page4,session,day,update_time', 'nas_behaviour_visitpath_page4']}

columns_info = {'cid':'str', 'sid':'str', 'referer':'format_url', 'page1':'format_url', 'page2':'format_url', 'page3':'format_url', 'page4':'format_url', 'day':'int', 'update_time':'int', 'session':'long'}    
if os.path.exists(file):
    table_info = columns_dict[level]
    columns = table_info[0]
    table_name = table_info[1]
    conn = MySQLdb.connect(host, user, password, db)
    cursor = conn.cursor()
    cursor.execute("SET NAMES utf8")
        
    c_l = columns.strip().split(',')
    args = ','.join(['%s' % i for i in c_l])
    args2 = ','.join(['%s' for i in c_l])
    lines = []
    update_time = int(time.time())
    with open(file) as f:
        for i in f:
            l = i.rstrip('\n').split('\001')
            if l[0] and l[1]:
                l.append(day)
                l.append(update_time)
                lines.append(tuple([eval("%s('''%s''')" % (columns_info[c_l[index]], j if j else '0')) for index, j in enumerate(l)]))
    if len(lines) > 0:
        sql = 'insert into %s(%s) values(%s)' % (table_name, args, args2)
        cursor.executemany(sql, tuple(lines))
        conn.commit()
        delete_sql = "delete from %s where day='%s' and update_time!=%s" % (table_name, day, update_time)
        cursor.execute(delete_sql)
        conn.commit()
    cursor.close()
    conn.close()
